<template>
    <div class="land-archives">
        <!-- 地图容器 -->
        <div id="amap" style="width:100%;height:100%;"></div>

        <!-- 搜索 bar -->
        <div class="map-toolbar">
            <span class="return" @click="handleReturn"></span>
            <input :value="keywords" placeholder="请输入搜索关键字..." autocomplete="false" @input="handleInput" />
            <span class="clear" @click="handleClearInput" v-if="showList.length > 0"></span>
            <span class="btn" @click="handleSearch" v-else>搜索</span>
            <span class="scan" @click="handleScan"></span>
        </div>

        <!-- 其他图层数据 -->
        <div class="result-popup" :class="{'is-visible': searchPanelVisible}">
            <!-- 流程记录 -->
            <div class="result-popup__process">
                <ProcessRecord 
                    :visible="tabVisible"
                    :landData="landData" 
                    @onRecordClick="handleRecordClick" 
                />
            </div>

            <!-- 操作手柄 -->
            <div class="result-popup__trigger">
                <span class="icon" @click="handleToggleResultPanel"></span>
                <span class="close" v-if="tabVisible" @click="handleTabClose"></span>
            </div>

            <!-- 内容区域 -->
            <div class="result-popup__body">
                <div class="slide-container" :style="{'transform': `translateX(${translateX})`}">
                    <!-- 1、搜索后的结果 列表 -->
                    <div class="slide-item result-list">
                        <template v-if="showList.length">
                            <div 
                                class="scroll_v"
                                v-infinite-scroll="loadNextPage"
                                :infinite-scroll-immediate="false"
                            >
                                <div class="result-list__wrapper">
                                    <div class="result-list__cell" v-for="item in showList" :key="item.id"
                                        @click="handleItemClick(item)">
                                        <div class="content">
                                            <div class="title">{{item.zl}}{{item.bsm}}地块</div>
                                            <div class="area">{{item.mj ? Number(item.mj * 0.0015).toFixed(2) : 0}}亩</div>
                                        </div>
                                        <div class="thumb">
                                            <img src="../../assets/images/placeholder.png" width="70" height="70"/>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </template>
                        <template v-else>
                            <div style="padding-top:50px;">
                                <Empty text="请输入内容进行搜索"></Empty>
                            </div>
                        </template>
                    </div>

                    <!-- 2、点击列表项 展示tab -->
                    <div class="slide-item result-tabs">
                        <div class="result-tabs__nav">
                            <span class="item" :class="{'is-active': activeTabIndex === 1}"
                                @click="handleTabChange(1)">基本信息</span>
                            <span class="item" :class="{'is-active': activeTabIndex === 2}"
                                @click="handleTabChange(2)">权属信息</span>
                            <span class="item" :class="{'is-active': activeTabIndex === 3}"
                                @click="handleTabChange(3)">规划信息</span>
                            <span class="item" :class="{'is-active': activeTabIndex === 4}"
                                @click="handleTabChange(4)">{{ tabLastItemName }}</span>
                        </div>

                        <!-- 基础信息 -->
                        <div class="result-tabs__panel" v-if="activeTabIndex === 1">
                            <TabBasic :landData="landData" />
                        </div>

                        <!-- 权属信息 -->
                        <div class="result-tabs__panel" v-if="activeTabIndex === 2">
                            <TabOwnership :landData="landData" />
                        </div>

                        <!-- 规划信息 -->
                        <div class="result-tabs__panel" v-if="activeTabIndex === 3">
                            <TabPlanning :landData="landData" />
                        </div>

                        <!-- 最后一个tab -->
                        <div class="result-tabs__panel" v-if="activeTabIndex === 4">
                            <TabProcess :recordData="processData" />
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
</template>

<script setup>
import ProcessRecord from './components/ProcessRecord.vue';
import TabBasic from './components/TabBasic.vue';
import TabOwnership from './components/TabOwnership.vue';
import TabPlanning from './components/TabPlanning.vue';
import TabProcess from './components/TabProcess.vue';
import Empty from './components/Empty.vue';
import { api_getDistrictServer, api_getLandsByCondition, api_getBussinessLand, api_getLandExtendInfo } from '@/api/map';
import useAppStore from '@/store/modules/app';

const appStore = useAppStore();
const { oldCode, pathValues } = appStore.regionData;

let map = null;

const showList = ref([]);

const total = ref(0);
const current = ref(1);
const pageSize = ref(10);

const id = ref(0); // 使用 marker点击事件 需要填写id
const title = 'map';
const loading = ref(false)
const translateX = ref('0')
const recordList = ref([])
const searchPanelVisible = ref(false)
const dataList = ref([])
const tabVisible = ref(false)
const activeTabIndex = ref(1)
const tabLastItemName = ref('')

const resultPolygon = ref(null);

// 初始化
function initMap() {
    let mapTimer = setInterval(() => {
        if (window.aMapLoaded) {
            clearInterval(mapTimer);
            mapTimer = null;

            map = new AMap.Map('amap', {
                center: [106.886, 32.59],
                zoom: 10,
            });

            map.on('complete', () => {
                // if (pathValues[2] && pathValues[2] === '511924') {
                    const level = pathValues.length;
                    getDistrict(level, pathValues[level - 1]);
                // }
            })
        }
    }, 100);
}

// 获取行政区范围json数据
function getDistrict(level, code) {    
    // const filter = level < 5 ? `parentcode = ${code} OR code = ${code}` : `code = ${code}`;
    let filter = "";
    if (level < 3) {
        filter = "parentcode = 511924";
    } else if (level < 5) {
        filter = `parentcode = ${code}`;
    } else {
        filter = `code = ${code}`;
    }
    api_getDistrictServer(filter).then((res) => {
        const len = res.features.length;
        if (len > 0) {
            res.features.forEach((i) => {
                addPolygon(i.geometry.coordinates, i.properties.code === code ? true : false, level);
            })
        }
    })
}

// 绘制行政区范围
function addPolygon(data, ifFit = false, level) {
    let polygon = new AMap.Polygon({
        path: data,
        fillColor: '#BAD9F3',
        strokeOpacity: 1,
        fillOpacity: 0.8,
        strokeColor: '#0091E2',
        strokeWeight: 2,
    });

    if (ifFit) {
        const bounds = polygon.getBounds();
        const mybounds = new AMap.Bounds([bounds.southWest.lng, bounds.southWest.lat], [bounds.northEast.lng,
            bounds.northEast.lat
        ])
        map.setBounds(mybounds, false, [120, 60, 30, 30]);
    } else {
        map.add(polygon);
    }

    if (level === 5) {
        map.add(polygon);
    }
}

// 绘制查询结果地块
function addResultPolygon(data) {
    removeResultPolygon();

    resultPolygon.value = new AMap.Polygon({
        path: data,
        fillColor: '#FFFF00',
        strokeOpacity: 1,
        fillOpacity: 1,
        strokeColor: '#FF4500',
        strokeWeight: 1,
    });
    map.add(resultPolygon.value);
    const bounds = resultPolygon.value.getBounds();
    const mybounds = new AMap.Bounds([bounds.southWest.lng, bounds.southWest.lat], [bounds.northEast.lng,
        bounds.northEast.lat
    ])
    map.setBounds(mybounds, false, [30, 30, 30, 30]);
}

// 清除绘制的查询结果地块
function removeResultPolygon() {
    if (resultPolygon.value !== null) {
        map.remove(resultPolygon.value);
        resultPolygon.value = null;
    }
}

const keywords = ref('');

// 输入关键字
function handleInput(e) {
    keywords.value = e.target.value;
}

// 输入查询事件
function handleSearch() {
    if (!keywords.value || keywords.value.length === 0) {
        return;
    }
    // 只有行政区划从文旅示范区开始的才能查询
    // if (pathValues[2] && pathValues[2] === '511924') {
        getQueryResultList(keywords.value, true);
        searchPanelVisible.value = true;
    // }
}

// 返回
function handleReturn() {
    uni.postMessage({
        data: {
            action: 'RETURN',
        }
    })
}

// 清除搜索
function handleClearInput() {
    keywords.value = '';
    showList.value = [];
    searchPanelVisible.value = false;
    landData.value = {};
    processData.value = {};
    handleTabClose();

    map.setZoom(10);
    map.setCenter([106.886, 32.59])
    // iMap.removeSearchResultLayer();
}

// 扫描
function handleScan() {
    uni.postMessage({
        data: {
            action: 'SCAN',
        }
    })
}

// 查询地块
function getQueryResultList(keywords, ifReSearch) {
    const params = {
        zldm: oldCode,
        input: keywords,
        page: current.value,
        pageSize: pageSize.value,
        type: 0,
    }
    api_getLandsByCondition(params).then((res) => {
        if (ifReSearch) showList.value = [...res.records];
        else showList.value = [...toRaw(showList.value), ...res.records];
        total.value = res.total;
        current.value = res.current;
    });
}

// 查询结果列表滚动条触发事件
const loadNextPage = () => {
    if (pageSize.value * current.value < total.value) {
        current.value += 1;
        getQueryResultList(keywords.value, false);
    }
};

// 获取单条记录的信息
const landData = ref({});
const processData = ref({});
function handleItemClick(itemData) {
    api_getBussinessLand(itemData.bsm, itemData.gtdcbsm).then((res) => {
        if (res?.length > 0) {
            addResultPolygon(res[0].geometry.coordinates);

            api_getLandExtendInfo({ bsm: itemData.bsm }).then(res => {
                if (res.data) {
                    const resData = res.data;

                    landData.value = resData;

                    // 默认 记录第一条
                    const firstData = resData.list[0];
                    processData.value = firstData;
                    tabLastItemName.value = firstData.name.includes('违约记录') ? '违约记录' : firstData.name;

                    tabVisible.value = true;
                }        
            })
        }
    });

    translateX.value = '-50%';
    tabVisible.value = true;
}

function handleToggleResultPanel() {
    searchPanelVisible.value = !searchPanelVisible.value;
}

// 关闭tab
function handleTabClose() {
    translateX.value = '0';
    tabVisible.value = false;
}

// 切换tab
function handleTabChange(index) {
    activeTabIndex.value = index;
}

// 点击单条 记录 回调函数
function handleRecordClick(data) {
    processData.value = data;
    console.log('data: ', data)
    handleTabChange(4);
    tabLastItemName.value = data.name.includes('违约记录') ? '违约记录' : data.name;
    tabVisible.value = true;
}

onMounted(() => {
    // 清除地图数据
    map && (map = undefined);

    // 注意：异步回调函数的声明应该在 JSAPI 引入之前，函数名与callback=onLoad中对应
    initMap();
})
</script>

<style lang="scss" scoped>
.land-archives {
    position: relative;
    display: flex;
    width: 100%;
    height: 100vh;
    overflow: hidden;
}

.map-toolbar {
	height: 30px;
	background-color: #fff;
	box-shadow: 0 2px 4px 0 rgba(97, 127, 155, 0.3);
	border-radius: 10px;
	position: fixed;
	z-index: 100;
	left: 10px;
	right: 10px;
	top: 44px;
	padding: 10px 15px 10px 10px;
	box-sizing: content-box;
	display: flex;
	align-items: center;

    .return {
        width: 30px;
        height: 30px;
        background: url('../../assets/images/return@2x.png') no-repeat center center;
		background-size: contain;
    }

	input {
        height: 30px;
        line-height: 30px;
		flex: 1;
        border: none;
        outline: 0;
		margin: 0 15px 0 10px;
		font-size: 15px;
		color: #666;
	}

	.btn {
        width: 32px;
        height: 30px;
        line-height: 30px;
        text-align: center;
		font-size: 15px;
		color: #0096CF;
		font-weight: 600;
	}

    .clear {
        width: 20px;
        height: 20px;
        background: url('../../assets/images/clear@2x.png') no-repeat center center;
		background-size: contain;
    }

	.scan {
		width: 20px;
		height: 20px;
		background: url('../../assets/images/scan@2x.png') no-repeat center center;
		background-size: contain;
		margin-left: 20px;
	}
}

.result-popup {
	position: fixed;
	left: 0;
	right: 0;
	bottom: -400px;
	z-index: 999;
	// background-color: #fff;
	border-top-left-radius: 20px;
	border-top-right-radius: 20px;
	display: flex;
	flex-direction: column;
	transition: all .3s;

	// 流程记录
	&__process {
		height: 180px;
		margin-bottom: 10px;
		transition: all .3s;

		.process-wrapper {
			width: 140px;
			transform: translateX(-140px);
			opacity: 0;
			border: 1px solid #FFFFFF;
			background: rgba(255, 255, 255, 0.6);
			padding: 10px 5px 10px 10px;
			transition: all .3s;
		}

		.process-item {
			position: relative;

			.legend {
				display: flex;
				align-items: center;
				padding-left: 18px;
				position: relative;

				&::before {
					content: '';
					position: absolute;
					width: 10px;
					height: 10px;
					background: #FFFFFF;
					border-radius: 50%;
					border-style: solid;
					border-width: 2px;
					left: 0;
					top: 50%;
					transform: translateY(-50%);
				}

				.title {
					font-size: 14px;
					color: #333;
					font-weight: 600;
					margin-right: 4px;
				}

				.tag {
					padding: 1px 4px;
					border: solid 1px rgba(238, 72, 68, 0.60);
					background-color: rgba(255, 238, 237, 1);
					border-radius: 4px;
					color: #EE4844;
					font-size: 12px;
					margin-right: 6px;
				}

				.arrow {
					width: 0;
					height: 0;
					border-style: solid;
					border-width: 6px;
					border-color: transparent transparent transparent #A8B0BC;
				}

				&.red {
					&::before {
						border-color: #EE4844;
					}
				}

				&.orange {
					&::before {
						border-color: #FE9611;
					}
				}

				&.blue {
					&::before {
						border-color: #1890FF;
					}
				}
			}

			.content {
				padding: 10px 18px 15px;
				position: relative;

				&::after {
					content: '';
					position: absolute;
					width: 1px;
					left: 6px;
					top: -5px;
					bottom: 0;
					border-left: dashed 1px #AAB3C0;
				}

				.time {
					font-size: 12px;
					color: #7C869C;
				}
			}
		}

		&.is-visible {
			.process-wrapper {
				opacity: 1;
				transform: translateX(0);
			}
		}
	}

	// 控制手柄
	&__trigger {
		height: 26px;
		background-color: #0096CF;
		display: flex;
		justify-content: center;
		align-items: center;
		border-top-left-radius: 20px;
		border-top-right-radius: 20px;
		position: relative;

		.icon {
			width: 60px;
			height: 26px;
			background: url('../../assets/images/handler@2x.png') no-repeat center center;
			background-size: 30px 6px;
			transition: all .3s;
			transform: rotate(-180deg);
		}

		.close {
            width: 12px;
            height: 12px;
            background: url('../../assets/images/close@2x.png') no-repeat center center;
			background-size: contain;
			position: absolute;
			top: 50%;
			transform: translateY(-50%);
			right: 17px;
		}
	}

	// 内容区域
	&__body {
		height: 400px;
		transition: all .3s;
		overflow: hidden;
		background-color: #fff;

		.slide-container {
			width: 200%;
			height: 400px;
			display: flex;
			transition: all .3s;
		}

		.slide-item {
			width: 100%;
			height: 400px;
		}

		.scroll_v {
			height: 400px;
			transition: all .3s;
            overflow-y: auto;
            &::-webkit-scrollbar-thumb {
                background-color: #e1e6ec;
            }

            &::-webkit-scrollbar-thumb:hover {
                background-color: rgba(144, 147, 153, 0.5);
            }
		}
	}

	// 结果列表
	.result-list {
		height: 400px;
		overflow: hidden;

		&__wrapper {
			padding: 15px;
		}

		&__cell {
			display: flex;
			overflow: hidden;
			padding-bottom: 15px;
			margin-bottom: 15px;
			border-bottom: solid 1px #eee;

			.thumb {
				width: 70px;
				height: 70px;
				margin-left: 10px;
				flex-shrink: 0;

				image {
					width: 100%;
					height: 100%;
				}
			}

			.content {
				flex: 1;

				.title {
					font-size: 16px;
					line-height: 150%;
					color: #333;
					font-weight: 600;
				}

				.area {
					display: flex;
					align-items: center;
					justify-content: space-between;
					font-size: 12px;
					color: #999;
					margin-top: 5px;
				}
			}
		}
	}

	// tabs
	.result-tabs {
		display: flex;
		flex-direction: column;

		&__nav {
			display: flex;
			align-items: center;
			position: relative;

			&::after {
				content: '';
				width: 100%;
				height: 1px;
				background-color: #EBEBEB;
				position: absolute;
				left: 0;
				right: 0;
				bottom: 0;
			}

			.item {
				width: 25%;
				height: 40px;
				line-height: 40px;
				font-size: 15px;
				color: #333;
				text-align: center;
				position: relative;
				z-index: 3;

				&::after {
					content: '';
					width: 0;
					height: 2px;
					opacity: 0;
					position: absolute;
					bottom: 0;
					left: 50%;
					transform: translateX(-50%);
					transition: all .3s;
				}

				&.is-active {
					color: #0096CF;
					font-weight: 600;

					&::after {
						width: 60px;
						height: 2px;
						background-color: #0096CF;
						opacity: 1;
					}
				}
			}
		}

		&__panel {}

		.tab-scroll {
			height: 0;
			transition: all .3s;
		}

		.cell-group {
			background-color: #fff;
			padding: 10px 15px;

			&__legend {
				height: 51px;
				padding-left: 23px;
				padding-right: 15px;
				display: flex;
				align-items: center;
				background-color: #F3F4F8;
				font-size: 15px;
				color: #333;
				font-weight: 600;
				position: relative;

				&::before {
					content: '';
					width: 3px;
					height: 15px;
					background-color: #0096CF;
					position: absolute;
					left: 15px;
					top: 50%;
					transform: translateY(-50%);
				}
			}

			&__row {
				display: flex;
				align-items: center;
				height: 30px;
				line-height: 30px;
				font-size: 14px;

				.label {
					color: #333;
				}

				.content {
					color: #666;
				}

				.download {
					text-decoration: underline;
					color: #077CB1;
				}
			}
		}
	}

	&.is-visible {
		bottom: 0;

		.result-popup__trigger {
			.icon {
				transform: rotate(0deg);
			}
		}

		.result-popup__body {
			height: 400px;

			.scroll_v {
				height: 400px;
			}
		}

		.result-tabs {
			.tab-scroll {
				height: 360px;
			}
		}
	}

	.loading {
		width: 100%;
		height: 100%;
		display: flex;
		justify-content: center;
		align-items: center;

		.spinner {
			animation: rotate 2s infinite linear;
		}
	}

	@keyframes rotate {
		from {
			transform: rotate(0deg);
		}

		to {
			transform: rotate(360deg);
		}
	}
}
</style>